<template>
  <div class="table-wrapper">
    <header ref="tableWrapperHeader" class="table-header-wrapper">
      <SecurityCheckHeader
        title="航空货物综合统计"
        @change="changeHandler"
        @search="searchHandler"
        @exportex="exportex"
      />
    </header>
    <main>
      <SecurityCheckTable
        id="2"
        :footerDate="footerDate"
        :table-cols="tableCols"
        :table-data="tableData"
        row-key="index"
        :height="tableHeight"
        show-summary
        :pagination="false"
        :loading="loading"
      />
    </main>
  </div>
</template>

<script>
import SecurityCheckHeader from '../components/securityCheckHeader.vue'
import SecurityCheckTable from '../components/securityCheckTable.vue'
import { comprehensive } from '@/api/statistics/statistics.js'
import XLSX from 'xlsx'
import FileSaver from 'file-saver'
export default {
  components: { SecurityCheckHeader, SecurityCheckTable },
  data() {
    return {
      loading: false,
      tableHeight: '50vh',
      tableCols: [
        {
          dataIndex: 'no',
          key: 'no',
          title: '序号',
        },
        {
          dataIndex: 'risk',
          key: 'risk',
          title: '等级',
        },
        {
          dataIndex: 'num',
          key: 'num',
          title: '货物件数',
          clickHandler: (row, rowIndex) => {
            this.$router.push({
              path: './waybillTable',
              name: 'WaybillTable',
              params: {
                startTime: this.FormData.startTime,
                endTime: this.FormData.endTime,
                destination: this.FormData.destination,
                agentCode: this.FormData.agentCode,
                agentLevel: this.FormData.agentLevel,
                riskRating: row.risk,
                openResult: this.FormData.openResult,
              },
            })
          },
        },
        {
          dataIndex: 'kxsNum',
          key: 'kxsNum',
          title: '开箱件数',
        },
        {
          dataIndex: 'unpackResult',
          key: 'unpackResult',
          title: '开箱结果',
          children: [
            {
              dataIndex: 'fxNum',
              key: 'fxNum',
              title: '放行',
              clickHandler: (row, rowIndex) => {
                this.$router.push({
                  path: './waybillTable',
                  name: 'WaybillTable',
                  params: {
                    startTime: this.FormData.startTime,
                    endTime: this.FormData.endTime,
                    destination: this.FormData.destination,
                    agentCode: this.FormData.agentCode,
                    agentLevel: this.FormData.agentLevel,
                    riskRating: row.risk,
                    openResult: '放行',
                  },
                })
              },
            },
            {
              dataIndex: 'jyNum',
              key: 'jyNum',
              title: '拒运',
              clickHandler: (row, rowIndex) => {
                this.$router.push({
                  path: './waybillTable',
                  name: 'WaybillTable',
                  params: {
                    startTime: this.FormData.startTime,
                    endTime: this.FormData.endTime,
                    destination: this.FormData.destination,
                    agentCode: this.FormData.agentCode,
                    agentLevel: this.FormData.agentLevel,
                    riskRating: row.risk,
                    openResult: '拒运',
                  },
                })
              },
            },
            {
              dataIndex: 'yjNum',
              key: 'yjNum',
              title: '移交',
              clickHandler: (row, rowIndex) => {
                this.$router.push({
                  path: './waybillTable',
                  name: 'WaybillTable',
                  params: {
                    startTime: this.FormData.startTime,
                    endTime: this.FormData.endTime,
                    destination: this.FormData.destination,
                    agentCode: this.FormData.agentCode,
                    agentLevel: this.FormData.agentLevel,
                    riskRating: row.risk,
                    openResult: '移交',
                  },
                })
              },
            },
          ],
        },
      ],
      footerDate: [
        {
          no: '合计',
        },
      ],
      tableData: [],
      FormData: {
        destination: '', // 目的站
        agentCode: '', //代理人ID
        agentLevel: '', //代理人信用等级 A\B\C\D
        riskRating: '', //综合风险等级评估 低风险\优先\普通\高风险\严控
        startTime: '', //开始时间
        endTime: '', //结束时间
      },
    }
  },
  created() {
    this.formatDate()
  },
  mounted() {
    this.setTableHeight()
    window.addEventListener('resize', this.setTableHeight)
  },
  activated() {
    if (Object.keys(this.$route.params).length !== 0) {
      const { startTime, endTime, agentLevel, agentCode } = this.$route.params
      this.FormData.startTime = startTime
      this.FormData.endTime = endTime
      this.FormData.agentLevel = agentLevel
      this.FormData.agentCode = agentCode
    }
    this.getData()
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.setTableHeight)
  },
  methods: {
    //导出
    async exportex() {
      // let that = this;
      // this.$confirm({
      //   title: "是否确认导出",
      //   content: "此操作将导出当前条件下所有数据而非选中数据",
      //   onOk() {
      //     return comprehensivexcel(this.FormData).then((response) => {
      //       that.download(response.msg);
      //       that.$message.success("导出成功", 3);
      //     });
      //   },
      // });
      this.downFile()
    },
    downFile() {
      var wb = XLSX.utils.table_to_book(document.querySelector('#table2'))
      var wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        bookSST: true,
        type: 'array',
      })
      try {
        FileSaver.saveAs(
          new Blob([wbout], {
            type: 'application/octet-stream',
          }),
          '航空货物综合统计.xlsx'
        )
      } catch (e) {
        if (typeof console !== 'undefined') console.log(e, wbout)
      }
      return wbout
    },
    formatDate() {
      let date = new Date()
      let myyear = date.getFullYear()
      let mymonth = date.getMonth() + 1
      let myweekday = date.getDate()
      mymonth < 10 ? (mymonth = '0' + mymonth) : mymonth
      myweekday < 10 ? (myweekday = '0' + myweekday) : myweekday
      this.FormData.startTime = `${myyear}-${mymonth}-${myweekday}`
      this.FormData.endTime = `${myyear}-${mymonth}-${myweekday}`
    },
    //接口数据
    async getData() {
      try {
        this.loading = true
        const result = await comprehensive(this.FormData)
        if (result.code === 200) {
          this.tableData = result.data
          let num = []
          let kxsNum = []
          let fxNum = []
          let jyNum = []
          let yjNum = []
          this.tableData.forEach((res) => {
            res.num ? num.push(res.num) : num.push(0)
            res.kxsNum ? kxsNum.push(res.kxsNum) : kxsNum.push(0)
            res.fxNum ? fxNum.push(res.fxNum) : fxNum.push(0)
            res.jyNum ? jyNum.push(res.jyNum) : jyNum.push(0)
            res.yjNum ? yjNum.push(res.yjNum) : yjNum.push(0)
          })
          this.footerDate[0].num = eval(num.join('+'))
          this.footerDate[0].kxsNum = eval(kxsNum.join('+'))
          this.footerDate[0].fxNum = eval(fxNum.join('+'))
          this.footerDate[0].jyNum = eval(jyNum.join('+'))
          this.footerDate[0].yjNum = eval(yjNum.join('+'))
          this.loading = false
        }
      } catch (error) {
        console.log(error)
      }
    },
    changeHandler() {
      // this.$router.push({
      //   path: './cargoStatistics',
      //   query: this.FormData,
      // })
      let param = JSON.parse(JSON.stringify(this.FormData))
      this.$router.push({
        path: './cargoStatistics',
        name: 'CargoStatistics',
        params: param,
      })
    },
    searchHandler(arr) {
      this.FormData.startTime = arr[0][0]
      this.FormData.endTime = arr[0][1]
      this.FormData.agentLevel = arr[1]
      this.FormData.agentCode = arr[2]
      this.getData()
    },
    setTableHeight() {
      const topBarHeight = 80
      const headerHeight = this.$refs['tableWrapperHeader'].offsetHeight
      const footerBlackHeight = 24
      this.tableHeight = `calc(100vh - ${topBarHeight + headerHeight + footerBlackHeight}px)-20px`
    },
  },
}
</script>

<style lang="scss" scoped>
.table-wrapper {
  padding: 0 24px;
  // background: #dfe3ea;
  .table-header-wrapper {
    padding-top: 24px;
  }
}
</style>
